package com.tm.car.controller.car;

import com.tm.car.enums.ResultMap;
import com.tm.car.service.LoginService;
import com.tm.car.service.UserService;
import com.tm.car.utils.Md5Util;
import org.apache.catalina.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/car")
public class CarIndexController {
    private final LoginService loginService;

    private final HttpServletRequest request;

    private final UserService userService;


    public CarIndexController(LoginService loginService, HttpServletRequest request, UserService userService) {
        this.loginService = loginService;
        this.request = request;
        this.userService = userService;
    }

/*    @PostMapping("/login")
    @ResponseBody
    public ResultMap<Integer> login(User user) {

        user = loginService.login(user, request);

        request.getSession().setAttribute("user", user);

       return  null;
    }*/

    @GetMapping("/index")
    public String index() {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            user = (User) request.getSession().getAttribute("schoolUser");
            if (user != null) {
                request.getSession().setAttribute("user", user);
            }
        }
        if (user == null) {
            return "redirect:/car/login";
        } else {
            return "/car/index";
        }
    }

    @PostMapping("/login")
    @ResponseBody
    public ResultMap<Integer> login(User user) {

        user = loginService.login(user, request);

        request.getSession().setAttribute("user", user);

        return new ResultMap<Integer>().ok();
    }

    @GetMapping("/login")
    public String loginPage() {
        User user = (User) request.getSession().getAttribute("user");
        if (user != null) {
            return "redirect:/car/index";
        }
        return "/car/login";
    }

    @PostMapping("/change/pwd")
    @ResponseBody
    public ResultMap<String> changePwd(@RequestParam String pwdOld, @RequestParam String pwdOne, @RequestParam String pwdTwo) throws GlobalCustomerException {
        User user = (User) request.getSession().getAttribute("user");
        user.setPassword(pwdOld);
        User verifyUser = loginService.login(user, request);
        if (verifyUser == null) {
            throw new GlobalCustomerException("旧密码输入错误");
        }
        if (!pwdOne.equals(pwdTwo)) {
            throw new GlobalCustomerException("两次密码输入不一致");
        }
        user.setPassword(Md5Util.getMd5Str(pwdOne));
        if (userService.updateById(user)) {
            request.getSession().removeAttribute("user");
        }
        return new ResultMap<String>().succ("密码已修改，请重新登录");
    }
}
